package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import sun.misc.BASE64Encoder

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.SimpleDateFormat
/**
 * 创建法大大合同接口
 * 推送甲方/乙方签署
 */

public class apiCreateContract implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiCreateContract.class);
    private static String APPKEY;
    private static String APPID;
    private static String URL;
    private String charset = "utf-8"; // 设置字符集
    private int timeout = 100000; // 设置请求超时时间
    private int enableSSLflag = 0;
    private String LOCALURL = "";
    private String CALLBACKURL = "";
    private String Skip_FDD_API_Flag = "";

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        long startTime = System.currentTimeMillis();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        String v_interfacetype = request.getParameter("interfacetype");

        // 初始化返回参数
        JSONObject results = new JSONObject();
        JSONObject resultJson = null;
        //接收客户端调用参数
        String callJson = "";
        InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
        BufferedReader iny = new BufferedReader(reader);
        String line;
        while ((line = iny.readLine()) != null) {
            callJson += line;
        }
        log.info("[调用请求信息]:" + callJson);

        // 先获取系统配置是否跳过法大大接口
        Skip_FDD_API_Flag = KHDBConfig.getParamConfig(eliteBean, "Skip_FDD_API_Flag");
        log.debug("获取系统配置是否跳过法大大接口:" + Skip_FDD_API_Flag);

        JSONObject inJson = JSONObject.fromObject(callJson);
        LOCALURL = KHDBConfig.getAPIURL(eliteBean, "Groovy-Inner");
        URL = KHDBConfig.getAPIURL(eliteBean, "fddurl");
        CALLBACKURL = KHDBConfig.getAPIURL(eliteBean, "callbackip");
        APPKEY = KHDBConfig.getParam(eliteBean, "FDDKEY");
        APPID = KHDBConfig.getParam(eliteBean, "FDDID");

        log.info("[调用请求信息v_interfacetype类型]:" + v_interfacetype);
        if (v_interfacetype == "create") {      //合同创建

            if (Skip_FDD_API_Flag.equals("0")) {
                //获取工单id
                String workorderid = inJson.getString("workorderid");
                //获取合同ID
                String contractid = inJson.getString("contractid");
                //获取客户编号
                String customerID = inJson.getString("customerID");
                //获取客户类型
                String customertype = inJson.getString("customerType");//1,客户 2.企业
                //获取合同模板id
                String ModelID = inJson.getString("ModelID");
                //获取获取企业编号
                String companyCustomerid = inJson.getString("signature");
                //获取甲方
                String PartyA = inJson.getString("PartyA");
                //获取填充参数
                JSONObject assembly = inJson.getJSONObject("data");

                getAssembly(ModelID);

                List<Object> assList = new ArrayList();
                JSONObject assemblyPara = new JSONObject();
                Iterator<String> keys = assembly.keys();

                while (keys.hasNext()) {
                    String teams = keys.next();
                    log.debug("teams: " + teams);
                    assemblyPara.put("name", teams);
                    assemblyPara.put("value", assembly.getString(teams));
                    log.debug("assemblyPara:" + assemblyPara);
                    assList.add(assemblyPara.toString());
                    assemblyPara.clear();
                }
                log.debug("assList:" + assList.toString());

                JSONObject fillContracts = fillContract(eliteBean, assList, ModelID, workorderid, customerID, companyCustomerid, contractid);
                if (fillContracts.getString("code") != "1") {
                    results = fillContracts;
                } else {
                    results.put("code", "1");
                    results.put("msg", "合同生成成功");
                }
            } else {
                results.put("code", "1");
                results.put("msg", "合同生成成功(系统配置跳过法大大接口,默认法大大成功)");
            }

        } else if (v_interfacetype == "push") {     //推送乙方签署
            if (Skip_FDD_API_Flag.equals("0")) {
                //获取工单id
                String workorderid = inJson.getString("workroderid");
                results = pushCustomer(eliteBean, workorderid);

            } else {
                results.put("code", "1");
                results.put("msg", "推送乙方签署成功");
            }
        } else if (v_interfacetype == "pushAdmin") {     //推送甲方签署
            if (Skip_FDD_API_Flag.equals("0")) {
                //获取工单id
                String workorderid = inJson.getString("workroderid");
                results = pushAdmin(eliteBean, workorderid);

            } else {
                results.put("code", "1");
                results.put("msg", "推送甲方签署成功");
            }
        } else {
            results.put("code", "-1");
            results.put("msg", "interfacetype类型不存在");
        }

        return results.toString();
    }

    //推送甲方签署
    public JSONObject pushAdmin(EliteBean eliteBean, String workorderid) {
        JSONObject jsonPara = new JSONObject();
        HashMap<String, Object> headMap = new HashMap<>();
        headMap.put("Content-Type", "application/json");
        String autoArchive = "";
        //结果标识
        JSONObject pushresults = new JSONObject();
        //查询工单所需推送甲方--查排序最低且未推送甲方
        List custlist = eliteBean.chaxun_sql("select agreementduid, customerid, customertype, ht_type, contractid, f1.ordernum, ff.FDDGroup_id from fdd_agreement_list f1 left join fdd_contract_file ff on f1.ModelID = ff.contractfileid left join (select min(ordernum) as ordernum from fdd_agreement_list where ht_type!='客户' and pushsigning='未推送' and workorderid='" + workorderid + "')f2 on f1.ordernum=f2.ordernum where ht_type != '客户' and customerid is not null and workorderid = '" + workorderid + "' and pushsigning = '未推送' and f2.ordernum is not null", "dataSource");
        //查询工单所需推送甲方最大数字
        List maxcustlist = eliteBean.chaxun_sql("select max(ordernum) as ordernum from fdd_agreement_list where workorderid = '" + workorderid + "'", "dataSource");
        String maxordernum = maxcustlist[0].get("ordernum").toString();

        for (int i = 0; i < custlist.size(); i++) {
            String ht_type = custlist[i].get("ht_type");
            String agreementduid = custlist[i].get("agreementduid");
            String contractid = custlist[i].get("contractid");
            String customerid = custlist[i].get("customerid");
            String minordernum = custlist[i].get("ordernum").toString();
            String fddgroup_id = custlist[i].get("FDDGroup_id"); //合同模板类型
            //是否自动归档
            if (maxordernum == minordernum) {
                autoArchive = "1";
            } else {
                autoArchive = "2";
            }
            //查询推送甲方类型对应法大大个人编号、企业编号、签字位置、时间位置
            List fdd_list = eliteBean.chaxun_sql("select customerid, companyCustomerid, seal_location, date_location from fdd_admin where customerid = '" + customerid + "' and fdd_type = '" + ht_type + "' order by ordernum asc", "dataSource");
            //企业签署时：个人客户编号不传，则默认推送给企业管理员代表企业签署；个人客户编号有传，则该个人代表企业签署
            String fddcustomerid = fdd_list[0].get("customerid");
            String companyCustomerid = fdd_list[0].get("companyCustomerid");
            //甲方盖章处
            String seal_location = fdd_list[0].get("seal_location");
            //甲方签章日期
            String date_location = fdd_list[0].get("date_location");

            //平台交易号--用于签署回调唯一标识            --旧(System.currentTimeMillis()+i)/1000;
            String transactionNo = Util.getMD5Str(agreementduid);
            jsonPara.put("customerId", fddcustomerid);
            jsonPara.put("companyCustomerId", companyCustomerid);
            jsonPara.put("docNo", contractid);
            jsonPara.put("autoArchive", autoArchive);
            jsonPara.put("transactionNo", transactionNo);
            //甲方签署后回调地址
            jsonPara.put("notifyUrl", CALLBACKURL + "/api/apiContractCallback?callbacktype=admin");
            jsonPara.put("companyKeyWord", seal_location);
            jsonPara.put("companyKeywordStrategy", 0);

            /*
            JSONObject jsondatePara = new JSONObject();
            jsondatePara.put("keyword", date_location);ls
            jsondatePara.put("keywordStrategy", 0);
            jsonPara.put("dateSealKeywordDTO", jsondatePara);
            */
            if (fddgroup_id == "VBFWBF") { //如果合同模板类型是解除合同，则推送时间章关键字
                //签署时间：传时间章关键字
                JSONObject jsondatePara = new JSONObject();
                jsondatePara.put("keyword", KHDBConfig.getParam(eliteBean, "JFHTQS")); //时间章关键字
                jsondatePara.put("keywordStrategy", 0);
                jsondatePara.put("keywordOffsetX", 30);
                jsondatePara.put("keywordOffsetY", 50 * i);
                jsonPara.put("dateSealKeywordDTO", jsondatePara);
            }

            String bizContent = getbizContent(jsonPara.toString());
            bizContent = bizContent.replaceAll("\\n", "").replaceAll("\\r", ""); ;
            JSONObject jsons = new JSONObject();
            String datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            jsons.put("timestamp", datetime);
            jsons.put("bizContent", bizContent);
            jsons.put("signType", "SHA256");
            jsons.put("appId", APPID);
            String signString = "appId=" + APPID + "&bizContent=" + bizContent + "&signType=SHA256&timestamp=" + datetime;
            signString = signString.replace("\\n", "");

            String signstr1 = Util.getSHA256Str(signString).toUpperCase();
            String signstr2 = Util.getSHA256Str(signstr1 + APPKEY).toUpperCase();
            String sign = new BASE64Encoder().encodeBuffer(signstr2.getBytes("UTF-8"));
            jsons.put("sign", sign);
            log.debug("推送门户签署参数:" + jsons.toString().replace("\\n", ""));
            String Assemblys = Util.doHttpPostUseHead(URL + "/sign/portal-url/push", jsons.toString().replace("\\n", ""), charset, timeout, enableSSLflag, headMap);
            log.debug("推送门户签署返回:" + Assemblys.toString());
            JSONObject obj = JSONObject.fromObject(Assemblys);
            //如果code为1则标识当前客户已推送，等待签署后回调
            if (obj.getString("code") == '1') {
                eliteBean.update("update fdd_agreement_list set pushsigning = '已推送', pushsigningtime = now(), transactionNo = '" + transactionNo + "' where agreementduid = '" + agreementduid + "'", "dataSource");
            } else {
                eliteBean.update("update fdd_agreement_list set pushFailReason = '" + obj.getString("msg") + "', pushFailTime = now(), transactionNo = '" + transactionNo + "' where agreementduid = '" + agreementduid + "'", "dataSource");
                pushresults.put("code", "-1");
                pushresults.put("msg", "存在未成功推送");
            }
        }
        pushresults.put("code", "1");
        pushresults.put("msg", "推送甲方成功");
        return pushresults;
    }

    //推送乙方签署
    public JSONObject pushCustomer(EliteBean eliteBean, String workorderid) {
        JSONObject obj = new JSONObject();
        HashMap<String, Object> headMap = new HashMap<>();
        headMap.put("Content-Type", "application/json");
        //查询工单所需推送客户
        List custlist = eliteBean.chaxun_sql("select fl.agreementduid, fl.customerid, fl.customertype, fl.contractid, ff.FDDGroup_id from fdd_agreement_list fl left join fdd_contract_file ff on fl.ModelID = ff.contractfileid where fl.ht_type = '客户' and fl.customerid is not null and fl.pushsigning = '未推送' and fl.workorderid = '" + workorderid + "' ", "dataSource");

        log.info("[乙方签署的客户信息custlist]:" + custlist);
        for (int i = 0; i < custlist.size(); i++) {
            JSONObject jsonPara = new JSONObject();

            //客户类型,缺省传个人
            String customerid = custlist[i].get("customerid");
            String customertype = custlist[i].get("customertype").toString();
            String agreementduid = custlist[i].get("agreementduid");
            String contractid = custlist[i].get("contractid");
            String fddgroup_id = custlist[i].get("FDDGroup_id"); //合同模板类型
            String transactionNo = Util.getMD5Str(agreementduid);  //传参处理

            log.info("乙方客户类型customertype：" + customertype);
            if (customertype == "2") { //企业
                jsonPara.put("companyCustomerId", customerid);
                //平台交易号--用于签署回调唯一标识            --旧(System.currentTimeMillis()+i)/1000;
                jsonPara.put("docNo", contractid);
                jsonPara.put("autoArchive", "2");
                jsonPara.put("transactionNo", transactionNo);
                jsonPara.put("notifyUrl", CALLBACKURL + "/api/apiContractCallback?callbacktype=cust");
                /*
                 //20230727修改：客户类型为企业的需盖公章及法人签名，传2个关键字
                 jsonPara.put("companyKeyWord", "乙方签名处");
                 jsonPara.put("companyKeyWordStrategy", 0);
                 jsonPara.put("companyKeyWordOffsetX", 30);
                 jsonPara.put("companyKeyWordOffsetY", 50*i);
                */
                //第一个关键字，公司盖章
                Map<String, String> CompanySealKeywordDTO1 = new HashMap<String, String>();
                CompanySealKeywordDTO1.put("companyKeyWord", KHDBConfig.getParam(eliteBean, "YFQYGZ")); //关键字
                CompanySealKeywordDTO1.put("companyKeywordStrategy", 0);
                CompanySealKeywordDTO1.put("companyKeywordOffsetX", 30);
                CompanySealKeywordDTO1.put("companyKeywordOffsetY", 50 * i);
                CompanySealKeywordDTO1.put("sealName", KHDBConfig.getParam(eliteBean, "GONGZ")); //印章名称
                //第二个关键字，法人签名
                Map<String, String> CompanySealKeywordDTO2 = new HashMap<String, String>();
                CompanySealKeywordDTO2.put("companyKeyWord", KHDBConfig.getParam(eliteBean, "YFQYQM")); //关键字
                CompanySealKeywordDTO2.put("companyKeywordStrategy", 0);
                CompanySealKeywordDTO2.put("companyKeywordOffsetX", 30);
                CompanySealKeywordDTO2.put("companyKeywordOffsetY", 50 * i);
                CompanySealKeywordDTO2.put("sealName", KHDBConfig.getParam(eliteBean, "FANRZ")); //印章名称
                //将关键字拼接成list
                List<String> companySealInfoslist = new ArrayList<>();
                companySealInfoslist.add(CompanySealKeywordDTO1);
                companySealInfoslist.add(CompanySealKeywordDTO2);
                jsonPara.put("companySealInfos", companySealInfoslist);

                if (fddgroup_id == "VBFWBF") { //如果合同模板类型是解除合同，则推送时间章关键字
                    //签署时间：传时间章关键字
                    JSONObject jsondatePara = new JSONObject();
                    jsondatePara.put("keyword", KHDBConfig.getParam(eliteBean, "YFHTQS")); //时间章关键字
                    jsondatePara.put("keywordStrategy", 0);
                    jsondatePara.put("keywordOffsetX", 30);
                    jsondatePara.put("keywordOffsetY", 50 * i);
                    jsonPara.put("dateSealKeywordDTO", jsondatePara);
                }

            } else { //个人
                jsonPara.put("customerId", customerid);
                //平台交易号--用于签署回调唯一标识            --旧(System.currentTimeMillis()+i)/1000;
                jsonPara.put("docNo", contractid);
                jsonPara.put("autoArchive", "2");
                jsonPara.put("transactionNo", transactionNo);
                jsonPara.put("notifyUrl", CALLBACKURL + "/api/apiContractCallback?callbacktype=cust");
                //关键字设置
                jsonPara.put("personKeyWord", KHDBConfig.getParam(eliteBean, "YFQMC")); //关键字
                jsonPara.put("personKeywordStrategy", 0);
                jsonPara.put("personKeywordOffsetX", 30);
                jsonPara.put("personKeywordOffsetY", 50 * i);

                if (fddgroup_id == "VBFWBF") { //如果合同模板类型是解除合同，则推送时间章关键字
                    //签署时间：传时间章关键字
                    JSONObject jsondatePara = new JSONObject();
                    jsondatePara.put("keyword", KHDBConfig.getParam(eliteBean, "YFHTQS")); //时间章关键字
                    jsondatePara.put("keywordStrategy", 0);
                    jsondatePara.put("keywordOffsetX", 30);
                    jsondatePara.put("keywordOffsetY", 50 * i);
                    jsonPara.put("dateSealKeywordDTO", jsondatePara);
                }
            }

            String bizContent = getbizContent(jsonPara.toString());
            bizContent = bizContent.replaceAll("\\n", "").replaceAll("\\r", "");
            JSONObject jsons = new JSONObject();
            String datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            jsons.put("timestamp", datetime);
            jsons.put("bizContent", bizContent);
            jsons.put("signType", "SHA256");
            jsons.put("appId", APPID);
            String signString = "appId=" + APPID + "&bizContent=" + bizContent + "&signType=SHA256&timestamp=" + datetime;
            signString = signString.replace("\\n", "");
            log.debug("signString:" + signString);
            String signstr1 = Util.getSHA256Str(signString).toUpperCase();
            String signstr2 = Util.getSHA256Str(signstr1 + APPKEY).toUpperCase();
            String sign = new BASE64Encoder().encodeBuffer(signstr2.getBytes("UTF-8"));
            jsons.put("sign", sign);
            log.debug("【推送乙方参数】：" + jsons.toString().replace("\\n", ""));

            String Assemblys = "";
            //调用法大大推送签署接口，文档编号HT103
            if (customertype == "2") {  //20230828调整：推送两个印章的调用法大大定制接口
                Assemblys = Util.doHttpPostUseHead(URL + "/sign/portal-url/push/customized", jsons.toString().replace("\\n", ""), charset, timeout, enableSSLflag, headMap);
            } else {
                Assemblys = Util.doHttpPostUseHead(URL + "/sign/portal-url/push", jsons.toString().replace("\\n", ""), charset, timeout, enableSSLflag, headMap);
            }
            log.debug("【乙方签署接口返回】：" + Assemblys);
            obj = JSONObject.fromObject(Assemblys);

            //如果code为1则标识当前客户已推送，等待签署后回调
            if (obj.getString("code") == '1') {
                eliteBean.update("update fdd_agreement_list set pushsigning = '已推送', transactionNo = '" + transactionNo + "', pushsigningtime = now() where agreementduid = '" + agreementduid + "'", "dataSource");
                eliteBean.update("update objective set signingresults = '客户未签署' where workorderid = '" + workorderid + "'", "dataSource");
            } else {
                eliteBean.update("update fdd_agreement_list set pushFailReason = '" + obj.getString("msg") + "', pushFailTime = now(), transactionNo = '" + transactionNo + "' where agreementduid = '" + agreementduid + "'", "dataSource");
            }
        }
        return obj;
    }

    //编辑模板填充
    public JSONObject fillContract(EliteBean eliteBean, List assList, String ModelID, String workorderid, String customerID, String companyCustomerid, contractid) {
        JSONObject jsonPara = new JSONObject();
        HashMap<String, Object> headMap = new HashMap<>();
        headMap.put("Content-Type", "application/json");
        List businessnumberlist = eliteBean.chaxun_sql("select businessnumber from objective where workorderid = '" + workorderid + "'", "dataSource");
        String businessnumber = "";
        if (businessnumberlist.size() > 0) {
            businessnumber = businessnumberlist[0].get("businessnumber");
        }

        jsonPara.put("id", ModelID);
        jsonPara.put("contractTitle", businessnumber);
        jsonPara.put("contractNo", contractid);
        //jsonPara.put("personCustomerId","a59cdbf03fbd4f47a358814c1a574d10");
        //jsonPara.put("companyCustomerid","36d29f1c90c143c7a29f2b672936fad9");
        jsonPara.put("personCustomerId", "");
        jsonPara.put("companyCustomerId", companyCustomerid);//personCustomerId
        jsonPara.put("onlineWidgetDetailDTOS", assList);
        jsonPara.put("crossPlatform", 1);//因法大大改版新增
        String bizContent = getbizContent(jsonPara.toString());
        log.debug("编辑模板填充参数1:" + jsonPara.toString());
        bizContent = bizContent.replaceAll("\\n", "").replaceAll("\\r", ""); ;

        JSONObject jsons = new JSONObject();
        String datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        jsons.put("timestamp", datetime);
        jsons.put("bizContent", bizContent);
        jsons.put("signType", "SHA256");
        jsons.put("appId", APPID);
        String signString = "appId=" + APPID + "&bizContent=" + bizContent + "&signType=SHA256&timestamp=" + datetime;
        signString = signString.replace("\\n", "");

        String signstr1 = Util.getSHA256Str(signString).toUpperCase();
        String signstr2 = Util.getSHA256Str(signstr1 + APPKEY).toUpperCase();
        String sign = new BASE64Encoder().encodeBuffer(signstr2.getBytes("UTF-8"));
        jsons.put("sign", sign);
        log.debug("编辑模板填充参数:" + jsons.toString().replace("\\n", ""));

        String Assemblys = Util.doHttpPostUseHead(URL + "/online-template/fill", jsons.toString().replace("\\n", ""), charset, timeout, enableSSLflag, headMap);
        log.debug("合同生成返回结果:" + Assemblys.toString());
        JSONObject obj = JSONObject.fromObject(Assemblys);
        return obj;
    }

    //获取合同模板控件
    public JSONObject getAssembly(String Modelid) {
        JSONObject jsonPara = new JSONObject();
        HashMap<String, Object> headMap = new HashMap<>();
        headMap.put("Content-Type", "application/json");

        jsonPara.put("id", Modelid);
        String bizContent = getbizContent(jsonPara.toString());
        bizContent = bizContent.replaceAll("\\n", "").replaceAll("\\r", "");

        JSONObject jsons = new JSONObject();
        String datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        jsons.put("timestamp", datetime);
        jsons.put("bizContent", bizContent);
        jsons.put("signType", "SHA256");
        jsons.put("appId", APPID);
        String signString = "appId=" + APPID + "&bizContent=" + bizContent + "&signType=SHA256&timestamp=" + datetime;
        signString = signString.replace("\\n", "");
        log.debug("signString:" + signString);
        String signstr1 = Util.getSHA256Str(signString).toUpperCase();
        log.debug("signstr1:" + signstr1);
        log.debug("signstr1:" + signstr1 + APPKEY);
        String signstr2 = Util.getSHA256Str(signstr1 + APPKEY).toUpperCase();
        log.debug("signstr2:" + signstr2);
        String sign = new BASE64Encoder().encodeBuffer(signstr2.getBytes("UTF-8"));
        jsons.put("sign", sign);
        log.debug("合同模板控件参数:" + jsons.toString().replace("\\n", ""));
        String Assemblys = Util.doHttpPostUseHead(URL + "/online-template/widget/list", jsons.toString().replace("\\n", ""), null, timeout, enableSSLflag, headMap);
        log.debug("Assemblys:" + Assemblys)
        JSONObject obj = JSONObject.fromObject(Assemblys);
        return obj;
    }

    //获取bizContent
    public String getbizContent(String param) {
        log.debug("param:" + param);
        String encodedObject = URLEncoder.encode(param, "UTF-8");
        String biz_contents = new BASE64Encoder().encodeBuffer(encodedObject.getBytes("UTF-8"));
        log.info("[biz_contents]:" + biz_contents);
        return biz_contents;
    }

}